const { storage } = require("@/lib/storage");

function observeCdIframeContent(iframe, url) {
    try {
        // 获取 iframe 的内容文档
        let iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        if (!iframeDoc) {
            console.warn('Cannot access iframe content');
            return;
        }

        // 检查是否有目标元素
        let toolbars = iframeDoc.querySelectorAll('.detail-actions .toolbar');
        if (toolbars.length > 0) {
            let toolbar = toolbars[toolbars.length - 1];
            // 彻底防止重复：先移除当前 toolbar 内所有 id=addAWorkTask 的按钮
            let oldBtns = toolbar.querySelectorAll('#addAWorkTask');
            oldBtns.forEach(btn => btn.remove());
            let dividers = toolbar.getElementsByClassName("divider");
            if (dividers.length > 0) {
                const newContent = `
                            <a href="#" class="toolbar-item btn ghost" data-app="product" id="addAWorkTask">
                                <i class="icon icon-doc"></i>
                                <span class="text">添加任务计划</span>
                            </a>
                        `;
                const lastDivider = dividers[0];
                lastDivider.insertAdjacentHTML('afterend', newContent);

                // 添加点击事件监听器
                const addWorkTaskButton = toolbar.querySelector('#addAWorkTask');
                if (addWorkTaskButton) {
                    addWorkTaskButton.addEventListener('click', (event) => {
                        event.preventDefault(); // 阻止默认行为
                        chrome.storage.local.set({
                            'addTask': {
                                url: url,
                                title: iframeDoc.querySelector('.entity-title-text').textContent,
                            }
                        })
                        chrome.runtime.sendMessage({ action: "createTab", url: chrome.runtime.getURL('home.html') });
                    });
                }
                return; // 找到目标后退出
            }
        }
    } catch (e) {
        console.warn('Error observing iframe content:', e);
    }
}

function observeAlEmailIframeContent(iframe, content) {
    // 创建全屏加载遮罩
    const loadingOverlay = document.createElement('div');
    loadingOverlay.id = 'loading-overlay';
    loadingOverlay.style.position = 'fixed';
    loadingOverlay.style.top = '0';
    loadingOverlay.style.left = '0';
    loadingOverlay.style.width = '100%';
    loadingOverlay.style.height = '100%';
    loadingOverlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
    loadingOverlay.style.zIndex = '9999';
    loadingOverlay.style.display = 'flex';
    loadingOverlay.style.justifyContent = 'center';
    loadingOverlay.style.alignItems = 'center';
    loadingOverlay.style.color = '#fff';
    loadingOverlay.style.fontSize = '20px';
    loadingOverlay.textContent = '正在准备数据...';
    document.body.appendChild(loadingOverlay);

    let cs = content.split('\n');
    setTimeout(() => {
        let title = document.querySelector('label[aria-label="主题"]').querySelector('input');
        title.value = cs[0].trim() + '-周报-' + formatDate(new Date());
        // 触发 input 事件
        const inputEvent = new Event('input', {
            bubbles: true,
            cancelable: true
        });
        title.dispatchEvent(inputEvent);

        try {
            // 获取 iframe 的内容文档
            let iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
            if (!iframeDoc) {
                console.warn('Cannot access iframe content');
                document.body.removeChild(loadingOverlay); // 移除遮罩
                return;
            }
            let html = '';
            cs.forEach((line) => {
                html += `<div style="clear: both;">${line}<br></div>`;
            });

            // 检查是否有目标元素
            let contenteditable = iframeDoc.querySelector('body[contenteditable=true]');
            if (contenteditable) {
                contenteditable.innerHTML = html;
                setTimeout(() => {
                    document.querySelector('.e_editor_toolbar_item[_id=decreaseindent]').click();
                    setTimeout(() => {
                        document.querySelector('.e_editor_toolbar_item[_id=decreaseindent]').click();
                        setTimeout(() => {
                            document.querySelector('label[aria-label="收件人"]').querySelector('input').click();
                            document.body.removeChild(loadingOverlay); // 移除遮罩
                            storage.remove("plane-daily-report")
                        }, 1000);
                    }, 500);
                }, 500);
            } else {
                document.body.removeChild(loadingOverlay); // 移除遮罩
            }
        } catch (e) {
            console.warn('Error observing iframe content:', e);
            document.body.removeChild(loadingOverlay); // 移除遮罩
        }
    }, 500);
}

/**
 * 添加禅道菜单
 * @param {*} url 
 * @returns 
 */
function addCdToolbar(url) {
    let iframes = document.getElementsByTagName('iframe');
    if (iframes.length === 0) {
        // 定义并初始化 MutationObserver
        const observer = new MutationObserver((mutationsList) => {
            for (let mutation of mutationsList) {
                let iframes = document.getElementsByTagName('iframe');
                for (let iframe of iframes) {
                    observeCdIframeContent(iframe, url); // 对新插入的 iframe 启动观察
                    observer.disconnect(); // 停止观察
                    return
                }
            }
        });
        // 监听主文档的变化，检测 iframe 的插入
        observer.observe(document.body, { childList: true, subtree: true });
        return;
    }
    for (let iframe of iframes) {
        observeCdIframeContent(iframe, url);
    }
}


const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}/${month}/${day}`;
};

/**
 * 处理阿里
 * @param {*} url 
 * @returns 
 */
function handleAlEmailToolbar(url) {
    storage.get("plane-daily-report").then(r => {

        if (!r) {
            return
        }

        let iframes = document.getElementsByClassName('e_iframe');
        if (iframes.length === 0) {
            // 定义并初始化 MutationObserver
            const observer = new MutationObserver((mutationsList) => {
                for (let mutation of mutationsList) {
                    let iframes = document.getElementsByClassName('e_iframe');
                    for (let iframe of iframes) {
                        observeAlEmailIframeContent(iframe, r); // 对新插入的 iframe 启动观察
                        observer.disconnect(); // 停止观察
                        return
                    }
                }
            });
            // 监听主文档的变化，检测 iframe 的插入
            observer.observe(document.body, { childList: true, subtree: true });
            return;
        }
        for (let iframe of iframes) {
            observeAlEmailIframeContent(iframe, r);
        }
    });

}

// 消息交互
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (sender.id !== chrome.runtime.id) {
        return;
    }
    sendResponse("ok"); // 发送响应回内容脚本
});


function monitorUrlChange(callback) {
    // 通过 script.src 注入脚本，绕过 CSP 限制
    const script = document.createElement('script');
    script.src = chrome.runtime.getURL('js/inject-url-listener.js');
    script.onload = function () {
        this.remove();
        setTimeout(() => {
            callback(window.location.href);
        }, 1000);
    };
    (document.head || document.documentElement).appendChild(script);

    // content-script 监听自定义事件
    window.addEventListener('AvaUrlChange', function (e) {
        if (e && e.detail && e.detail.url) {
            callback(e.detail.url);
        }
    });

    // 首次进入也触发一次
    callback(window.location.href);
}

// 初始化 URL 变化监听
monitorUrlChange((newUrl) => {
    if (newUrl.startsWith("http://192.168.199.166/") && newUrl.includes('story-view') || newUrl.includes('task-view') || newUrl.includes('bug-view')) {
        addCdToolbar(newUrl);
    } else if (newUrl.startsWith("https://qiye.aliyun.com/") && newUrl.includes('/compose')) {
        handleAlEmailToolbar(newUrl);
    }
});
